#include "keyboard.h"



/*******************************************************************************
*    void KeyboardScan(void)
*******************************************************************************/

uInt8 KeyboardScan(void) {

  uInt8 result=NO_KEY;

               if (GetFlag(FLAG_KEYBOARD)) {

                    ClearFlag(FLAG_KEYBOARD);
                    SetFlag(FLAG_KEYBOARD_WAIT_FOR_RELEASE);
                    result =  GetKey();
               }
               if (GetFlag(FLAG_KEYBOARD_WAIT_FOR_RELEASE)){
                    Check_KeyboardRelease();
               }


return (result);

}
/*******************************************************************************
*    void Check_KeyboardRelease(void)
*******************************************************************************/

void Check_KeyboardRelease(void) {

        __delay_cycles(_50_MILLISECONDE);

        if ( GetKey() == NO_KEY) {
          Keyboard_enable();
          ClearFlag(FLAG_KEYBOARD_WAIT_FOR_RELEASE);
       }
}
/*******************************************************************************
*    uInt8 GetKey()(void)
*******************************************************************************/

uInt8 GetKey(void) {

    return( ((PIN_KEYBOARD >> 2) & NO_KEY));

}

/*******************************************************************************
//	void PCINT_RDS_enable(void)
*******************************************************************************/
void Keyboard_enable(void) {

    PCMSK0 |= (1 << PCINT_KEY_START) | (1 << PCINT_KEY_UP) | (1 << PCINT_KEY_DOWN) | (1 << PCINT_KEY_LEFT) | (1 << PCINT_KEY_RIGHT);
    EIMSK |= (1 << PCIE0);
    EIFR |= (1 << PCIF0);                 // Clear Pin Change Interrupt Flag 0
    ClearFlag(FLAG_KEYBOARD_DISABLE);

}

/*******************************************************************************
//	void PCINT_Keyboard_disable(void)
*******************************************************************************/
void Keyboard_disable(void) {

  PCMSK0 &= ~ ( (1 << PCINT_KEY_START) | (1 << PCINT_KEY_UP) | (1 << PCINT_KEY_DOWN) | (1 << PCINT_KEY_LEFT) | (1 << PCINT_KEY_RIGHT) );
  EIMSK &= ~(1 << PCIE0);          // disable pin change interrupts
  EIFR |= (1 << PCIF0);            // clear flag writing logical 1
  SetFlag(FLAG_KEYBOARD_DISABLE);
}


